import { useState, useEffect } from 'react';
import { Card, Descriptions, Button, Modal, Form, Input, message } from 'antd';
import { MainLayout } from '~/layouts/MainLayout';
import { useAuthStore } from '~/stores/auth';
import { authApi } from '~/services/api';

export default function Profile() {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const user = useAuthStore((state) => state.user);

  const handleChangePassword = async (values: any) => {
    try {
      setLoading(true);
      await authApi.changePassword({
        oldPassword: values.oldPassword,
        newPassword: values.newPassword
      });
      message.success('修改成功');
      setVisible(false);
      form.resetFields();
    } catch (error: any) {
      message.error(error.response?.data?.message || '修改失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <MainLayout>
      <div className="bg-white p-6 rounded-lg">
        <div className="flex justify-between mb-4">
          <h1 className="text-2xl">个人中心</h1>
          <Button type="primary" onClick={() => setVisible(true)}>
            修改密码
          </Button>
        </div>

        <Card>
          <Descriptions title="基本信息">
            <Descriptions.Item label="用户名">{user?.username}</Descriptions.Item>
            <Descriptions.Item label="角色">管理员</Descriptions.Item>
          </Descriptions>
        </Card>

        <Modal
          title="修改密码"
          open={visible}
          onCancel={() => setVisible(false)}
          footer={null}
        >
          <Form form={form} onFinish={handleChangePassword} layout="vertical">
            <Form.Item
              name="oldPassword"
              label="原密码"
              rules={[{ required: true }]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="newPassword"
              label="新密码"
              rules={[{ required: true }]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="confirmPassword"
              label="确认密码"
              rules={[
                { required: true },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item className="text-right mb-0">
              <Button type="primary" htmlType="submit" loading={loading}>
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </MainLayout>
  );
}